<?php

namespace Module\AdminApi\Api\Middleware;

use ModStart\Core\Input\InputPackage;
use ModStart\Core\Input\Request;
use ModStart\Core\Input\Response;

class AdminApiCheckMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        $input = InputPackage::buildFromInput();
        $apiKey = trim(Request::headerGet('admin-api-key'));
        if (empty($apiKey)) {
            $apiKey = $input->getTrimString('ADMIN_API_KEY');
        }
        if (empty($apiKey)) {
            return Response::generateError('对接Key为空，请传递 ADMIN_API_KEY 参数');
        }
        if ($apiKey != modstart_config('AdminApi_Key', '')) {
            return Response::generateError('对接Key错误');
        }
        return $next($request);
    }
}
